<template>
  <div class="grading-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <div>
            <el-button link @click="handleBack">
              <el-icon><ArrowLeft /></el-icon>
              返回
            </el-button>
            <span style="margin-left: 10px">判卷：{{ gradingDetail.paperName }}</span>
            <span style="margin-left: 20px; color: #909399">
              学生：{{ gradingDetail.studentName }}（{{ gradingDetail.studentUsername }}）
            </span>
          </div>
          <el-button type="primary" :loading="submitting" @click="handleSubmit">
            提交评分
          </el-button>
        </div>
      </template>

      <div v-loading="loading" element-loading-text="加载中..." class="grading-content-wrapper">
        <div v-if="!loading" class="grading-content">
          <div class="exam-info">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="试卷名称">{{ gradingDetail.paperName }}</el-descriptions-item>
              <el-descriptions-item label="学生姓名">{{ gradingDetail.studentName }}</el-descriptions-item>
              <el-descriptions-item label="学号">{{ gradingDetail.studentUsername }}</el-descriptions-item>
              <el-descriptions-item label="提交时间">{{ formatDateTime(gradingDetail.endTime) }}</el-descriptions-item>
            </el-descriptions>
          </div>

          <div class="questions-section">
            <div class="section-title">答题详情</div>

            <div
              v-for="(question, index) in gradingDetail.questions"
              :key="question.questionId"
              class="question-item"
            >
              <div class="question-header">
                <span class="question-number">第 {{ index + 1 }} 题</span>
                <span class="question-type">{{ getQuestionTypeLabel(question.type) }}</span>
                <span class="question-score">满分：{{ question.maxScore }} 分</span>
              </div>

              <div class="question-content">
                <div class="question-text">{{ question.content }}</div>

                <!-- 选择题显示选项 -->
                <div v-if="question.options" class="question-options">
                  <div
                    v-for="(option, key) in question.options"
                    :key="key"
                    class="option-item"
                  >
                    {{ key }}. {{ option }}
                  </div>
                </div>

                <!-- 正确答案和解析 -->
                <div v-if="question.type !== 'essay'" class="answer-info">
                  <div class="answer-row">
                    <span class="answer-label">正确答案：</span>
                    <span class="correct-answer">{{ question.correctAnswer }}</span>
                  </div>
                  <div v-if="question.analysis" class="analysis-section">
                    <div class="analysis-title">解析：</div>
                    <div class="analysis-content">{{ question.analysis }}</div>
                  </div>
                </div>

                <!-- 学生答案 -->
                <div class="student-answer-section">
                  <div class="answer-label">学生答案：</div>
                  <div class="student-answer-content">
                    {{ question.studentAnswer || '未作答' }}
                  </div>
                </div>

                <!-- 评分区域（只有主观题需要评分） -->
                <div v-if="question.type === 'essay'" class="grading-section">
                  <el-form-item label="得分" :rules="[{ required: true, message: '请输入得分' }]">
                    <el-input-number
                      v-model="gradingForm[question.questionId].score"
                      :min="0"
                      :max="question.maxScore"
                      :precision="2"
                      :step="0.5"
                      style="width: 200px"
                    />
                    <span style="margin-left: 10px; color: #909399">/ {{ question.maxScore }} 分</span>
                  </el-form-item>
                  <el-form-item label="评语">
                    <el-input
                      v-model="gradingForm[question.questionId].teacherComment"
                      type="textarea"
                      :rows="3"
                      placeholder="请输入评语（可选）"
                      maxlength="500"
                      show-word-limit
                    />
                  </el-form-item>
                </div>

                <!-- 已评分显示（客观题或已评分的主观题） -->
                <div v-if="question.type !== 'essay' || (question.score > 0 || question.teacherComment)" class="graded-info">
                  <div class="graded-row">
                    <span class="graded-label">得分：</span>
                    <span class="graded-score">{{ question.score }} 分</span>
                  </div>
                  <div v-if="question.teacherComment" class="graded-row">
                    <span class="graded-label">评语：</span>
                    <span class="graded-comment">{{ question.teacherComment }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { getExamForGrading, saveGrading, type GradingDetail, type GradingQuestion } from '../../api/exam'

const router = useRouter()
const route = useRoute()

const loading = ref(false)
const submitting = ref(false)
const gradingDetail = ref<GradingDetail>({
  examId: 0,
  paperId: 0,
  paperName: '',
  studentId: 0,
  studentName: '',
  studentUsername: '',
  startTime: '',
  endTime: '',
  questions: []
})

const gradingForm = reactive<Record<number, { score: number, teacherComment: string }>>({})

// 获取判卷详情
const fetchGradingDetail = async () => {
  loading.value = true
  try {
    const examId = parseInt(route.params.examId as string)
    const res = await getExamForGrading(examId)
    gradingDetail.value = res.data

    // 初始化评分表单
    gradingDetail.value.questions.forEach(q => {
      if (q.type === 'essay') {
        gradingForm[q.questionId] = {
          score: q.score || 0,
          teacherComment: q.teacherComment || ''
        }
      }
    })
  } catch (error: any) {
    ElMessage.error(error.message || '获取判卷详情失败')
    router.back()
  } finally {
    loading.value = false
  }
}

// 获取题目类型标签
const getQuestionTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    single: '单选题',
    multiple: '多选题',
    judge: '判断题',
    fill: '填空题',
    essay: '简答题'
  }
  return typeMap[type] || type
}

// 提交评分
const handleSubmit = async () => {
  try {
    // 验证所有主观题都已评分
    const essayQuestions = gradingDetail.value.questions.filter(q => q.type === 'essay')
    const ungradedQuestions = essayQuestions.filter(q => {
      const form = gradingForm[q.questionId]
      return !form || form.score === 0 || form.score === null || form.score === undefined
    })

    if (ungradedQuestions.length > 0) {
      ElMessage.warning('请为所有主观题评分后再提交')
      return
    }

    await ElMessageBox.confirm('确定要提交评分吗？提交后将无法修改。', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    submitting.value = true

    // 构建评分数据（只包含主观题）
    const gradingData = essayQuestions.map(q => ({
      questionId: q.questionId,
      score: gradingForm[q.questionId].score,
      teacherComment: gradingForm[q.questionId].teacherComment || ''
    }))

    await saveGrading(gradingDetail.value.examId, gradingData)
    ElMessage.success('评分提交成功')
    
    router.push({ name: 'GradingList' })
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '提交评分失败')
    }
  } finally {
    submitting.value = false
  }
}

// 返回
const handleBack = () => {
  router.push({ name: 'GradingList' })
}

// 格式化日期时间
const formatDateTime = (dateTimeStr: string) => {
  if (!dateTimeStr) return ''
  const date = new Date(dateTimeStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  fetchGradingDetail()
})
</script>

<style scoped>
.grading-container {
  padding: 20px;
  overflow: visible;
}

.grading-container :deep(.el-card) {
  overflow: visible;
  height: auto;
  max-height: none;
}

.grading-container :deep(.el-card__body) {
  overflow: visible;
  height: auto;
  max-height: none;
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.grading-content-wrapper {
  min-height: 400px;
}

.grading-content {
  overflow: visible;
}

.exam-info {
  margin-bottom: 30px;
}

.questions-section {
  margin-top: 30px;
  overflow: visible;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #409eff;
}

.question-item {
  margin-bottom: 30px;
  padding: 20px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.question-header {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.question-number {
  font-weight: bold;
  font-size: 16px;
}

.question-type {
  color: #409eff;
}

.question-score {
  margin-left: auto;
  color: #f56c6c;
  font-weight: bold;
}

.question-content {
  padding-left: 20px;
}

.question-text {
  font-size: 15px;
  line-height: 1.6;
  margin-bottom: 15px;
}

.question-options {
  margin: 15px 0;
}

.option-item {
  padding: 10px;
  margin-bottom: 8px;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.answer-info {
  margin: 15px 0;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.answer-row {
  margin-bottom: 10px;
}

.answer-label {
  font-weight: bold;
  margin-right: 10px;
}

.correct-answer {
  color: #67c23a;
  font-weight: bold;
}

.analysis-section {
  margin-top: 10px;
  padding: 10px;
  background-color: #f0f9ff;
  border-radius: 4px;
}

.analysis-title {
  font-weight: bold;
  margin-bottom: 8px;
  color: #409eff;
}

.analysis-content {
  line-height: 1.6;
  color: #606266;
}

.student-answer-section {
  margin: 20px 0;
  padding: 15px;
  background-color: #fafafa;
  border-radius: 4px;
  border-left: 4px solid #409eff;
}

.student-answer-content {
  margin-top: 10px;
  padding: 10px;
  background-color: #fff;
  border-radius: 4px;
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.6;
}

.grading-section {
  margin: 20px 0;
  padding: 20px;
  background-color: #fff7e6;
  border-radius: 4px;
  border: 2px solid #e6a23c;
}

.graded-info {
  margin: 15px 0;
  padding: 15px;
  background-color: #f0f9ff;
  border-radius: 4px;
}

.graded-row {
  margin-bottom: 10px;
}

.graded-row:last-child {
  margin-bottom: 0;
}

.graded-label {
  font-weight: bold;
  margin-right: 10px;
}

.graded-score {
  color: #409eff;
  font-weight: bold;
  font-size: 16px;
}

.graded-comment {
  color: #606266;
  line-height: 1.6;
}
</style>


